You want to be able to access the largest element in a stack.
You've already implemented this Stack class:
class Stack(object):
def __init__(self):
"""Initialize an empty stack"""
self.items = []
def push(self, item):
"""Push a new item onto the stack"""
self.items.append(item)
def pop(self):
"""Remove and return the last item"""
# If the stack is empty, return None
# (it would also be reasonable to throw an exception)
if not self.items:
return None
return self.items.pop()
def peek(self):
"""Return the last item without removing it"""
if not self.items:
return None
return self.items[-1]
Use your Stack class to implement a new class MaxStack with a method get_max() that returns the largest element in the stack. get_max() should not remove the item.
Your stacks will contain only integers.
We define two new stacks within our MaxStack class—stack holds all of our integers, and maxes_stack holds our "maxima." We use maxes_stack to keep our max up to date in constant time as we push() and pop():
class MaxStack(object):
def __init__(self):
self.stack = Stack()
self.maxes_stack = Stack()
def push(self, item):
"""Add a new item onto the top of our stack."""
self.stack.push(item)
# If the item is greater than or equal to the last item in maxes_stack,
# it's the new max! So we'll add it to maxes_stack.
if self.maxes_stack.peek() is None or item >= self.maxes_stack.peek():
self.maxes_stack.push(item)
def pop(self):
"""Remove and return the top item from our stack."""
item = self.stack.pop()
# If it equals the top item in maxes_stack, they must have been pushed
# in together. So we'll pop it out of maxes_stack too.
if item == self.maxes_stack.peek():
self.maxes_stack.pop()
return item
def get_max(self):
"""The last item in maxes_stack is the max item in our stack."""
return self.maxes_stack.peek()
time for push(), pop(), and get_max(). additional space, where is the number of operations performed on the stack.
Our solution requires additional space for the second stack. But do we really need it?
Can you come up with a solution that requires additional space? (It's tricky!)
Notice how in the solution we're spending time on push() and pop() so we can save time on get_max(). That's because we chose to optimize for the time cost of calls to get_max().
But we could've chosen to optimize for something else. For example, if we expected we'd be running push() and pop() frequently and running get_max() rarely, we could have optimized for faster push() and pop() methods.
Sometimes the first step in algorithm design is deciding what we're optimizing for. Start by considering the expected characteristics of the input.
Do you have an answer?
Wanna review this one again later? Or do you feel like you got it all?
Mark as done Pin for review laterReset editor
Powered by qualified.io